package com.ruoyi.web.controller.video;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.resource.domain.ResourceEnum;
import com.ruoyi.resource.domain.ResourceInfo;
import com.ruoyi.resource.service.IFileOperator;
import com.ruoyi.resource.service.IResourceInfoService;
import com.ruoyi.service.IVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/media")
public class VideoController {

    @Autowired
    IVideoService iVideoService;

    @Autowired
    IResourceInfoService iResourceInfoService;

    @Autowired
    IFileOperator iFileOperator;

    @Autowired
    private NonStaticResourceHttpRequestConfig nonStaticResourceHttpRequestConfig;

    //视频根目录
    @Value("${video.root}")
    private String folder;
    /**
     * 获取视频
     * @return 视频
     */
    @GetMapping("/video/{screenId}")
    @ResponseBody
    public void getVideo(@PathVariable Integer screenId, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        if(screenId == null||screenId>9||screenId<0) {
            return;
         }
        String addr = folder + '/' + screenId +".mp4";
        Path videoPath = Paths.get(addr);
        try {
            File video =  iVideoService.getVideoByAddress(addr);
        }catch (Exception e){
            e.printStackTrace();
            return;
        }
        //

//        String mimeType = Files.probeContentType(videoPath);
        request.setAttribute(NonStaticResourceHttpRequestConfig.ATTR_FILE, videoPath);
        nonStaticResourceHttpRequestConfig.handleRequest(request, response);

    }

    @PostMapping("/video/{screenId}")
    @ResponseBody
    public AjaxResult uploadVideo(@RequestParam("file")MultipartFile file,@PathVariable Integer screenId)   {

        if (file.isEmpty()) {
            return new AjaxResult(400, "视频上传失败");
        }

        if(screenId == null||screenId>9||screenId<0) {
            return new AjaxResult(400,"非法视频编号");
        }


        try {
            //先删除该位置原有的文件
            ResourceInfo resourceOrgInfo = iResourceInfoService.selectResourceInfoById(Long.valueOf(screenId));
            if (resourceOrgInfo == null) {
                //表信息为空,默认当前目录下没有文件,先插入一条初始化数据
                ResourceInfo initInfo = new ResourceInfo();
                initInfo.setId(Long.valueOf(screenId));
                initInfo.setResourceType(0L);
                initInfo.setHasResource(0L);
                initInfo.setScreenNumber(Long.valueOf(screenId));
                iResourceInfoService.insertResourceInfo(initInfo);
            }
            else if(resourceOrgInfo.getHasResource()==1){
                iFileOperator.DeleteFileByScreenId(screenId);
            }
            String fullPath = folder + '/' + screenId.toString() + ".mp4";
            File dest = new File(fullPath);
            file.transferTo(dest);
            ResourceInfo resourceInfo = new ResourceInfo();
            resourceInfo.setId(screenId.longValue());
            resourceInfo.setHasResource( Integer.valueOf(1).longValue());
            resourceInfo.setScreenNumber(screenId.longValue());
            resourceInfo.setResourceType(Integer.valueOf(ResourceEnum.VIDEO.getValue()).longValue());
            iResourceInfoService.updateResourceInfo(resourceInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(500, "服务器出现异常");
        }
        return new AjaxResult(200, "上传成功");
    }

    /**
     * 删除视频
     * @param screenId
     * @return
     */
    @DeleteMapping("/video/{screenId}")
    @ResponseBody
    public  AjaxResult deleteVideo(@PathVariable Integer screenId) {

        if(screenId == null||screenId>9||screenId<0) {
            return new AjaxResult(400,"非法视频编号");
        }
        String videoName = screenId + ".mp4";
        File dir = new File(folder);
        File[] files = dir.listFiles();
        assert files != null;
        for(File file : files){
            if(file.getName().equals(videoName)){
                boolean result = file.delete();
                if(result){
                    return  new AjaxResult(200,"删除成功");
                }else {
                    return new AjaxResult(500,"删除异常");
                }
            }
        }
        return  new AjaxResult(201,"文件不存在");
     }

    @GetMapping("/videoinfos/")
    @ResponseBody
    public List<String> getVideoList(){
        File dir = new File(folder);
        File[] files = dir.listFiles();
        assert files != null;
        List<String> videoList = new ArrayList<>();
        for(File file : files){
            String name = file.getName();
            if(name.endsWith(".mp4")) {
                videoList.add(name);
            }
        }
        return videoList;
    }


}
